/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.ouertech.android.agm.lib.ui.base;


import android.app.Dialog;
import android.content.res.TypedArray;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.MenuRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.ouertech.android.agm.lib.ui.R;
import com.ouertech.android.agm.lib.ui.widget.popup.PopupMenu;
import com.ouertech.android.agm.lib.ui.widget.tabhost.FragmentTabHost;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : Zhenshui.Xia
 * @date : 2015/7/16.
 * @desc : 基础UI activity
 */
public abstract class BaseUIActivity extends BaseActivity
        implements View.OnClickListener {
    //标题居左
    private static final int TOOLBAR_TITLE_GRAVITY_LEFT = 0;
    //标题居中
    private static final int TOOLBAR_TITLE_GRAVITY_CENTER = 1;

    //是否初始化过状态栏的背景
    private boolean mIsInitStatusBarColor;
    //系统栏背景是否可以被设置
    private boolean mSystembarEnabled;
    //系统栏背景颜色管理器
    private SystemBarTintManager mSbtManager;
    //界面构选项
    private long mOptions;
    //toolbar折叠layout
    private CollapsingToolbarLayout mCtlLayout;
    //工具栏（标题栏）
    private Toolbar mToolbar;
    //标题位置
    private int mTitleGravity;
    //标题
    private TextView mTvTitle;
    //导航图标点击事件监听器
    private MenuItem.OnMenuItemClickListener mNavigationListener;
    //menu集合
    private SparseArray<MenuBase> mMenus;

    //appbar自定义布局
    private int mAppCustomLayoutRes;
    //tablayout
    private TabLayout mTabLayout;
    //与appbar tab关联的fragments
    private List<FragmentTab> mAppTabs;
    private int mTabIndex;


    //
    private FrameLayout mFlContent;
    //
    private RecyclerView mUrvContent;
    //数据加载中
    private ProgressWheel mPwLoading;
    //暂无数据提示
    private TextView mTvEmpty;
    //网络请求重试
    private TextView mTvRetry;
    //网络请求重试监听器
    private OnRetryListener mRetryListener;

    //等待对话框
    private Dialog mWaitDialog;

    //navbar自定义布局
    private int mNavCustomLayoutRes;
    //tabhost
    private FragmentTabHost mTabHost;
    //与navbar tab关联的fragments
    private List<FragmentTab> mNavTabs;

    //
    private NavigationView mNvDrawer;
    private DrawerLayout mDlLayout;

    private View mViewShadow;

    /**
     * 网络请求重试监听器
     */
    public interface OnRetryListener {
        //重试
        public void onRetry();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mIsInitStatusBarColor = false;
        mSystembarEnabled = false;
        //获取构造的界面结构
        mOptions = initOptions();
        //初始化menu集合，最多支持8个menu
        mMenus = new SparseArray<>(8);
        mMenus.put(R.id.res_id_menu_item0, null);
        mMenus.put(R.id.res_id_menu_item1, null);
        mMenus.put(R.id.res_id_menu_item2, null);
        mMenus.put(R.id.res_id_menu_item3, null);
        mMenus.put(R.id.res_id_menu_item4, null);
        mMenus.put(R.id.res_id_menu_item5, null);
        mMenus.put(R.id.res_id_menu_item6, null);
        mMenus.put(R.id.res_id_menu_item7, null);
    }

    /**
     * 初始化界面构造选项
     * @return
     */
    protected long initOptions() {
        return UIOptions.UI_OPTIONS_SCREEN_DEFAULT;
    }

    /**
     * 初始化systembar
     */
    protected void initSystemBar() {

    }

    /**
     * 初始化Appbar custom
     */
    protected void initAppCustom() {

    }

    /**
     * 初始化appbar Toolbar
     */
    protected void initAppToobar(){

    }

    /**
     * 初始化appbar的tabs
     */
    protected void initAppTabs(){

    }

    /**
     * 初始化navigation bar
     */
    protected void initNavCustom(){

    }

    /**
     * 初始化navigation bar的tabs
     */
    protected void initNavTabs(){

    }

    /**
     * 初始化sliding page
     */
    protected void initDrawerView() {

    }


    protected void initBaseViews() {
        //================LAYOUT=================
        if(withOption(UIOptions.UI_OPTIONS_DRAWER)) {
            super.setContentView(R.layout.res_activity_base_drawer_ui);
            mNvDrawer = (NavigationView)findViewById(R.id.base_id_darwer);
            mDlLayout = (DrawerLayout)findViewById(R.id.base_id_drawer_layout);
            initDrawerView();
        } else {
            super.setContentView(R.layout.res_activity_base_ui);
        }

        //==============SYSTEMBAR===================
        int flags = getWindow().getAttributes().flags;
        int flagFullscreen = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if((flagFullscreen & flags) != flagFullscreen) {
            //有系统栏
            if(withOption(UIOptions.UI_OPTIONS_SYSTEMBAR)) {
                initSystemBar();

                if(!mIsInitStatusBarColor) {
                    setStatusBarResource(R.color.res_color_statusbar);
                }
            } else {//无系统栏
                getWindow().setFlags(flagFullscreen, flagFullscreen);
            }
        }


        //==================APPBAR==================
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM
                | UIOptions.UI_OPTIONS_APPBAR_TABS
                )) {

            ViewStub appbarStub = (ViewStub) findViewById(R.id.base_id_appbar_stub);
            if(withOption(UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)) {
                appbarStub.setLayoutResource(R.layout.res_layout_base_appbar_collapsed_toolbar);
            } else {
                appbarStub.setLayoutResource(R.layout.res_layout_base_appbar);
            }

            appbarStub.inflate();


            //初始化appbar toolbar
            if(withOption(UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)) {
                mCtlLayout = (CollapsingToolbarLayout)findViewById(R.id.base_id_appbar_collapsed_layout);
                mCtlLayout.setCollapsedTitleTextAppearance(R.style.res_style_toolbar_collapsed_title_text);
                mCtlLayout.setExpandedTitleTextAppearance(R.style.res_style_toolbar_expanded_title_text);
                mToolbar = (Toolbar)findViewById(R.id.base_id_appbar_toolbar);
                setSupportActionBar(mToolbar);
                getSupportActionBar().setDisplayShowTitleEnabled(false);
                initAppToobar();
            }else if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
                ViewStub toolbarStub = (ViewStub) findViewById(R.id.base_id_appbar_toolbar_stub);
                toolbarStub.setLayoutResource(R.layout.res_layout_base_appbar_toolbar);
                toolbarStub.inflate();

                mToolbar = (Toolbar)findViewById(R.id.base_id_appbar_toolbar);
                TypedArray a = obtainStyledAttributes(R.style.res_style_toolbar_title_gravity,
                        R.styleable.Toolbar);
                mTitleGravity = a.getInt(R.styleable.Toolbar_titleGravity, TOOLBAR_TITLE_GRAVITY_LEFT);
                a.recycle();

                if(mTitleGravity == TOOLBAR_TITLE_GRAVITY_CENTER) {
                    mTvTitle = (TextView) findViewById(R.id.base_id_appbar_toolbar_title);
                } else {
                    //设置默认的toolbar title样式
                    mToolbar.setTitleTextAppearance(this, R.style.res_style_toolbar_title_text);
                    //设置默认的toolbar subtitle样式
                    mToolbar.setSubtitleTextAppearance(this, R.style.res_style_toolbar_subtitle_text);
                }

                setSupportActionBar(mToolbar);
                getSupportActionBar().setDisplayShowTitleEnabled(false);

                initAppToobar();

                if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)) {
                    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
                    params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                            | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                }
            }

            //初始化appbar custom
            if(withOption(UIOptions.UI_OPTIONS_APPBAR_CUSTIOM)) {
                initAppCustom();
                if(mAppCustomLayoutRes > 0) {
                    ViewStub customStub = (ViewStub) findViewById(R.id.base_id_appbar_custom_stub);
                    customStub.setLayoutResource(mAppCustomLayoutRes);
                    View view = customStub.inflate();

                    if(!withOption(UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)
                        && withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)) {

                        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)){
                            ViewStub toolbarStub = (ViewStub) findViewById(R.id.base_id_appbar_toolbar_stub);
                            AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarStub.getLayoutParams();
                            params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                                    | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                        }

                        AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) view.getLayoutParams();
                        params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                                | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                    }
                }
            }

            //初始化appbar tabs
            if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)) {
                ViewStub tabsStub = (ViewStub) findViewById(R.id.base_id_appbar_tabs_stub);
                tabsStub.setLayoutResource(R.layout.res_layout_base_appbar_tabs);
                tabsStub.inflate();
                mTabLayout = (TabLayout) findViewById(R.id.base_id_appbar_tabs);
                initAppTabs();
            }
        }


        //==================CONTENT==================
        ViewStub contentStub = (ViewStub) findViewById(R.id.base_id_content_stub);
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)) {
            contentStub.setLayoutResource(R.layout.res_layout_base_content_viewpager);
            contentStub.inflate();

            mViewShadow = findViewById(R.id.base_id_content_shadow_top);
            ViewPager viewPager = (ViewPager) findViewById(R.id.base_id_content_viewpager);
            viewPager.setAdapter(new FragmentTabAdapter(getSupportFragmentManager(),
                    mAppTabs));
            mTabLayout.setupWithViewPager(viewPager);
            viewPager.setCurrentItem(mTabIndex);
        } else if(withOption(UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            contentStub.setLayoutResource(R.layout.res_layout_base_content_navtabs);
            contentStub.inflate();
            mViewShadow = findViewById(R.id.base_id_content_shadow_top);
        } else if(withOption(UIOptions.UI_OPTIONS_CONTENT_LIST
            | UIOptions.UI_OPTIONS_CONTENT_GRID
            | UIOptions.UI_OPTIONS_CONTENT_STAGGERED)){
            contentStub.setLayoutResource(R.layout.res_layout_base_content_recycler);
            contentStub.inflate();

            mViewShadow = findViewById(R.id.base_id_content_shadow_top);
            mUrvContent = (RecyclerView)findViewById(R.id.base_id_content_recycler);

            mPwLoading = (ProgressWheel)findViewById(R.id.base_id_content_progress);
            mTvEmpty = (TextView)findViewById(R.id.base_id_content_empty);
            mTvRetry = (TextView)findViewById(R.id.base_id_content_retry);
            mTvRetry.setOnClickListener(this);
        } else if(withOption(UIOptions.UI_OPTIONS_CONTENT_SCROLL)){
            contentStub.setLayoutResource(R.layout.res_layout_base_content_scroll);
            contentStub.inflate();

            mViewShadow = findViewById(R.id.base_id_content_shadow_top);
            mFlContent = (FrameLayout)findViewById(R.id.base_id_content_root);
            mPwLoading = (ProgressWheel)findViewById(R.id.base_id_content_progress);
            mTvEmpty = (TextView)findViewById(R.id.base_id_content_empty);
            mTvRetry = (TextView)findViewById(R.id.base_id_content_retry);

            mTvRetry.setOnClickListener(this);
        } else if(withOption(UIOptions.UI_OPTIONS_CONTENT_CUSTOM)){
            contentStub.setLayoutResource(R.layout.res_layout_base_content_custom);
            contentStub.inflate();

            mViewShadow = findViewById(R.id.base_id_content_shadow_top);
            mFlContent = (FrameLayout)findViewById(R.id.base_id_content_root);
            mPwLoading = (ProgressWheel)findViewById(R.id.base_id_content_progress);
            mTvEmpty = (TextView)findViewById(R.id.base_id_content_empty);
            mTvRetry = (TextView)findViewById(R.id.base_id_content_retry);

            mTvRetry.setOnClickListener(this);
        }

        if(mViewShadow != null) {
            if (withOption(UIOptions.UI_OPTIONS_SYSTEMBAR
                    | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM
                    | UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                    | UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR
                    | UIOptions.UI_OPTIONS_APPBAR_TABS)) {
                mViewShadow.setVisibility(View.VISIBLE);
            } else {
                mViewShadow.setVisibility(View.GONE);
            }
        }

        //==================NAVIGATIONBAR==================
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)
                && withOption(UIOptions.UI_OPTIONS_NAVBAR_TABS)) {//初始化Tab导航栏
            ViewStub navStub = (ViewStub) findViewById(R.id.base_id_navbar_stub);
            navStub.setLayoutResource(R.layout.res_layout_base_navbar_tabs);
            navStub.inflate();

            initNavTabs();
            //初始化Tabhost
            if(UtilList.isNotEmpty(mNavTabs)) {
                mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
                mTabHost.setup(this, getSupportFragmentManager(), R.id.base_id_content_root);

                for (int i = 0; i < mNavTabs.size(); i++) {
                    FragmentTab tab = mNavTabs.get(i);
                    mTabHost.addTab(mTabHost.newTabSpec(tab.getFragmentClazz().getName())
                                    .setIndicator(newTabIndicator(tab.getTitle(), tab.getIcon())),
                            tab.getFragmentClazz(), null);
                }

                mTabHost.getTabWidget().setDividerDrawable(null);
            }

        } else if(withOption(UIOptions.UI_OPTIONS_NAVBAR_CUSTOM)){ //初始化自定义导航栏
            initNavCustom();

            if(mNavCustomLayoutRes > 0) {
                ViewStub navStub = (ViewStub) findViewById(R.id.base_id_navbar_stub);
                navStub.setLayoutResource(mNavCustomLayoutRes);
                navStub.inflate();
            }
        }

    }

    /**
     * 系统栏背景是否可以被设置
     * @param enabled
     */
    public void setSystemBarEnabled(boolean enabled) {
        this.mSystembarEnabled = enabled;
    }

    /**
     * 设置状态栏背景颜色,支持api>=19
     * @param color
     */
    public void setStatusBarColor(int color) {
        if(!mSystembarEnabled
                || !withOption(UIOptions.UI_OPTIONS_SYSTEMBAR)) {
            return;
        }

        //android4.4以上的手机启用设置状态栏背景
        //系统导航栏背景默认不设置，并只支持api>=21以上设置，api 19、20也可以
        //做到设置系统导航栏背景，但会引起很多兼容性和体验问题
        mIsInitStatusBarColor = true;
        Window window = getWindow();
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT
                || Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT_WATCH) {
            //设置状态栏的默认背景颜色
            if(mSbtManager == null) {
                //设置透明状态栏
                WindowManager.LayoutParams params = window.getAttributes();
                params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                window.setAttributes(params);

                mSbtManager = new SystemBarTintManager(this);
                mSbtManager.setStatusBarTintEnabled(true);
            }

            mSbtManager.setStatusBarTintColor(color);
            mSbtManager.setStatusBarAlpha(Color.alpha(color));
        } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(color);
        }
    }

    /**
     * 设置状态栏背景颜色,支持api>=19
     * @param colorRes
     */
    public void setStatusBarResource(@ColorRes int colorRes) {
        setStatusBarColor(getResources().getColor(colorRes));
    }


    /**
     * 设置导航栏背景颜色,支持api>=21
     * @param color
     */
    public void setNavigationBarColor(int color) {
        if(!mSystembarEnabled
                || !withOption(UIOptions.UI_OPTIONS_SYSTEMBAR)) {
            return;
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(color);
        }
    }

    /**
     * 设置导航栏背景颜色,支持api>=21
     * @param colorRes
     */
    public void setNavigationBarResource(@ColorRes int colorRes) {
        setNavigationBarColor(getResources().getColor(colorRes));
    }


    /**
     * 设置标题
     * @param title
     */
    public void setTitle(String title) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)) {
            if(mCtlLayout != null) {
                mCtlLayout.setTitle(title);
            }
        } else if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
            if(mTitleGravity == TOOLBAR_TITLE_GRAVITY_CENTER) {
                if(mTvTitle != null) {
                    mTvTitle.setText(title);
                }
            } else {
                if(mToolbar != null ) {
                    mToolbar.setTitle(title);
                }
            }
        }
    }

    /**
     * 设置标题
     * @param txtRes
     */
    public void setTitle(@StringRes int txtRes) {
        setTitle(getString(txtRes));
    }

    /**
     * 设置子标题,居中模式暂不支持子标题
     * @param title
     */
    public void setSubTitle(String title) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)
                && mTitleGravity == TOOLBAR_TITLE_GRAVITY_LEFT
                && mToolbar != null) {
            mToolbar.setSubtitle(title);
        }
    }

    /**
     * 设置子标题
     * @param txtRes
     */
    public void setSubTitle(@StringRes int txtRes) {
        setSubTitle(getString(txtRes));
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param imgRes
     */
    public void setNavigation(@DrawableRes int imgRes) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));

        MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                finish();
                return false;
            }
        };

        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param drawable
     */
    public void setNavigation(Drawable drawable) {
        MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                finish();
                return false;
            }
        };

        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param imgRes
     * @param listener
     */
    public void setNavigation(@DrawableRes int imgRes, MenuItem.OnMenuItemClickListener listener) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));
        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param drawable
     * @param listener
     */
    public void setNavigation(Drawable drawable, MenuItem.OnMenuItemClickListener listener) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)) {
            return;
        }

        if(mToolbar != null) {
            mToolbar.setNavigationIcon(drawable);
        }

        mNavigationListener = listener;
    }

    /**
     * 显示标题栏logo
     * @param imgRes
     */
    public void setLogo(@DrawableRes int imgRes) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));
        setLogo(drawable);
    }

    /**
     * 显示标题栏logo
     * @param drawable
     */
    public void setLogo(Drawable drawable) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR)) {
            return;
        }

        if(mToolbar != null) {
            mToolbar.setLogo(drawable);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();

        for (int i = 0; i < mMenus.size(); i++) {
            MenuBase value = mMenus.valueAt(i);
            if (value != null) {
                if(value instanceof MenuTxt) {//添加文本menu
                    MenuTxt elem = (MenuTxt)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuImg) {//添加图片menu
                    MenuImg elem = (MenuImg)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setIcon(elem.getIcon());
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuSearch) {//添加搜索menu
                    MenuSearch elem = (MenuSearch)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    SearchView svSearch = new SearchView(this);
                    svSearch.setOnQueryTextListener(elem.getListener());
                    item.setActionView(svSearch);
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuPopup) {//添加popup menu
                    MenuPopup elem = (MenuPopup)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setIcon(elem.getIcon());
                    item.setShowAsAction(elem.getShowAsAction());
                }
            }
        }

        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        MenuBase value = mMenus.get(itemId);

        if(android.R.id.home == itemId) {
            if(mNavigationListener != null) {
                mNavigationListener.onMenuItemClick(item);
            }
        } else {
            if (value != null) {
                if (value instanceof MenuTxt) {//触发点击文本menu
                    MenuTxt elem = (MenuTxt) value;
                    MenuItem.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        listener.onMenuItemClick(item);
                    }
                } else if (value instanceof MenuImg) {//触发点击图片menu
                    MenuImg elem = (MenuImg) value;
                    MenuItem.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        listener.onMenuItemClick(item);
                    }
                } else if (value instanceof MenuPopup) {//触发打开popupmenu
                    MenuPopup elem = (MenuPopup) value;
                    View view = mToolbar.findViewById(elem.getMenuId());
                    PopupMenu popup = new PopupMenu(this, view);
                    MenuInflater inflater = popup.getMenuInflater();
                    inflater.inflate(elem.getMenuRes(), popup.getMenu());
                    popup.show();

                    PopupMenu.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        popup.setOnMenuItemClickListener(listener);
                    }
                }
            }
        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * 添加menu
     * @param menu
     */
    public void addMenu(@NonNull MenuBase menu) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_COLLAPSED_TOOLBAR) ) {
            return;
        }

        if(menu != null && mMenus.get(menu.getMenuId()) == null) {
            for (int i = 0; i < mMenus.size(); i++) {
                int key = mMenus.keyAt(i);
                if (mMenus.get(key) == null) {
                    menu.setMenuId(key);
                    mMenus.put(key, menu);
                    invalidateOptionsMenu();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏menu
     * @param menu
     */
    public void hideMenu(MenuBase menu){
        if(menu != null) {
            hideMenu(menu.getMenuId());
            menu.setMenuId(0);
        }
    }

    /**
     * 隐藏menu
     * @param menuId
     */
    public void hideMenu(int menuId){
        if(mMenus.get(menuId) != null) {
            mMenus.put(menuId, null);
            invalidateOptionsMenu();
        }
    }

    /**
     * 设置appbar通用布局的layout
     * @param layoutRes
     */
    public void setAppCustomLayout(@LayoutRes int layoutRes) {
        this.mAppCustomLayoutRes = layoutRes;
    }

    /**
     * 添加appbar上的文本tab
     * @param txtRes
     * @param cls
     */
    public void addAppTab(@StringRes int txtRes, Class<? extends BaseUIFragment> cls) {
        addAppTab(getString(txtRes), cls, null);
    }

    /**
     * 设置选中的tab
     * @param index
     */
    public void setAppTabIndex(int index) {
        this.mTabIndex = index;
    }

    /**
     * 设置tab的模式 TabLayout.MODE_FIXED  TabLayout.MODE_SCROLLABLE
     * @param mode
     */
    public void setAppTabMode(int mode) {
        if(mTabLayout != null) {
            mTabLayout.setTabMode(mode);
        }
    }

    /**
     * 设置tab的标题
     * @param index
     * @param title
     */
    public void setAppTabTitle(int index, String title) {
        if(mTabLayout != null) {
            mTabLayout.getTabAt(index).setText(title);
        }
    }

    /**
     * 设置tab的标题
     * @param index
     * @param txtRes
     */
    public void setAppTabTitle(int index, int txtRes) {
        setAppTabTitle(index, getString(txtRes));
    }

    /**
     * 添加appbar上的文本tab
     * @param title
     * @param cls
     */
    public void addAppTab(String title, Class<? extends BaseUIFragment> cls) {
        addAppTab(title, cls, null);
    }

    /**
     * 添加appbar上的文本tab
     * @param txtRes
     * @param cls
     * @param args
     */
    public void addAppTab(@StringRes int txtRes, Class<? extends BaseUIFragment> cls, Bundle args) {
        addAppTab(getString(txtRes), cls, args);
    }

    /**
     * 添加appbar上的文本tab
     * @param title
     * @param cls
     * @param args
     */
    public void addAppTab(String title, Class<? extends BaseUIFragment> cls, Bundle args) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TABS)
                || cls == null) {
            return;
        }

        if(mTabLayout != null && UtilString.isNotBlank(title)) {
            BaseUIFragment fragment = (BaseUIFragment) Fragment.instantiate(this, cls.getName(), args);
            if(mAppTabs == null) {
                mAppTabs = new ArrayList<>(4);
            }

            FragmentTab tab = new FragmentTab();
            tab.setTitle(title);
            tab.setFragment(fragment);
            mAppTabs.add(tab);
        }
    }

//    /**
//     * 设置list的适配器
//     * @param adapter
//     */
//    public void setContentListAdapter(AbsRecycleAdapter adapter) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_LIST)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//    /**
//     * 设置list的分割线
//     * @param decoration
//     */
//    public void setContentListDivider(RecyclerView.ItemDecoration decoration) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_LIST)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            mRvContent.addItemDecoration(decoration);
//        }
//    }
//
//    /**
//     * 设置grid的适配器
//     * @param adapter
//     */
//    public void setContentGridAdapter(AbsRecycleAdapter adapter, int spanCount) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_GRID)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            GridLayoutManager layoutManager = new GridLayoutManager(this, spanCount);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//
//    /**
//     * 设置grid的适配器
//     * @param adapter
//     * @param context
//     * @param attrs
//     * @param defStyleAttr
//     * @param defStyleRes
//     */
//    public void setContentGridAdapter(AbsRecycleAdapter adapter,
//                                      Context context, AttributeSet attrs, int defStyleAttr,
//                                      int defStyleRes) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_GRID)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            GridLayoutManager layoutManager = new GridLayoutManager(context,
//                    attrs, defStyleAttr, defStyleRes);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//    /**
//     * 设置grid的适配器
//     * @param adapter
//     * @param context
//     * @param spanCount
//     * @param orientation
//     * @param reverseLayout
//     */
//    public void setContentGridAdapter(AbsRecycleAdapter adapter,
//                                      Context context, int spanCount, int orientation,
//                                      boolean reverseLayout) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_GRID)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            GridLayoutManager layoutManager = new GridLayoutManager(context,
//                    spanCount, orientation, reverseLayout);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//
//    /**
//     * 设置grid的分割线
//     * @param decoration
//     */
//    public void setContentGridDivider(RecyclerView.ItemDecoration decoration) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_GRID)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            mRvContent.addItemDecoration(decoration);
//        }
//    }
//
//    /**
//     * 设置staggered的适配器
//     * @param adapter
//     * @param spanCount
//     * @param orientation
//     */
//    public void setContentStaggeredAdapter(AbsRecycleAdapter adapter,
//                                           int spanCount, int orientation) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_STAGGERED)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            StaggeredGridLayoutManager layoutManager =
//                    new StaggeredGridLayoutManager(spanCount, orientation);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//
//    /**
//     * 设置staggered的适配器
//     * @param adapter
//     * @param context
//     * @param attrs
//     * @param defStyleAttr
//     * @param defStyleRes
//     */
//    public void setContentStaggeredAdapter(AbsRecycleAdapter adapter,
//                                           Context context, AttributeSet attrs, int defStyleAttr,
//                                           int defStyleRes) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_STAGGERED)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            StaggeredGridLayoutManager layoutManager =
//                    new StaggeredGridLayoutManager(context, attrs, defStyleAttr, defStyleRes);
//            mRvContent.setLayoutManager(layoutManager);
//            mRvContent.setAdapter(adapter);
//        }
//    }
//
//
//    /**
//     * 设置瀑布流的分割线
//     * @param decoration
//     */
//    public void setContentStaggeredDivider(RecyclerView.ItemDecoration decoration) {
//        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_STAGGERED)) {
//            return;
//        }
//
//        if(mRvContent != null) {
//            mRvContent.addItemDecoration(decoration);
//        }
//    }
//
//
//    public void setRecyclerAdapter() {
//
//    }
//
//    public void setRecyclerDivider() {
//
//    }

    /**
     * 获取当前的recycler view
     * @return
     */
    public RecyclerView getRecyclerView() {
        return mUrvContent;
    }



    /**
     * 显示空数据文本提示
     * @param txtRes
     */
    public void setEmptyText(@StringRes int txtRes) {
        setEmptyText(getString(txtRes));
    }

    /**
     * 显示空数据文本提示
     * @param emptyText
     */
    public void setEmptyText(String emptyText) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS
                | UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            return;
        }

        if(mFlContent != null) mFlContent.setVisibility(View.GONE);
        if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
        if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
        if(mTvEmpty != null) {
            mTvEmpty.setVisibility(View.VISIBLE);
            mTvEmpty.setText(emptyText);
        }
    }

    /**
     * 隐藏空数据文本提示
     */
    public void hideEmptyText() {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS
                | UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            return;
        }

        if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
        if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
    }

    /**
     * 显示(隐藏)重试图标
     */
    public void setRetry(boolean enabled) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS
                | UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            return;
        }

        if (enabled) {
            if(mFlContent != null) mFlContent.setVisibility(View.GONE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.VISIBLE);
            if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
        } else {
            if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
        }
    }

    /**
     * 设置重试事件
     * @param listener
     */
    public void setOnRetryListener(OnRetryListener listener) {
        this.mRetryListener = listener;
    }

    /**
     * 显示(隐藏)加载过程
     */
    public void setLoading(boolean enabled) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TABS
                | UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            return;
        }

        if (enabled) {
            if(mFlContent != null) mFlContent.setVisibility(View.GONE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.VISIBLE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
            if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
        } else {
            if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
        }
    }


    @Override
    public void setContentView(@LayoutRes int layoutResId) {
        if(layoutResId > 0 ) {
            View view = LayoutInflater.from(this).inflate(layoutResId, null);
            setContentView(view);
        }
    }


    @Override
    public void setContentView(View view) {
        if(!withOption(UIOptions.UI_OPTIONS_CONTENT_CUSTOM
            | UIOptions.UI_OPTIONS_CONTENT_SCROLL)) {
            return;
        }

        if(view != null && mFlContent != null) {
            mFlContent.addView(view,
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.base_id_content_retry) {
            retry();
        }
    }

    /**
     * 显示等待对话框
     * @param enabled
     */
    public void setWaitingDialog(boolean enabled) {
        if(enabled) {
            if(mWaitDialog == null) {

                mWaitDialog = new AlertDialog.Builder(this, R.style.res_theme_dialog_waiting)
                        .setView(R.layout.res_layout_base_progress)
                        .show();
                mWaitDialog.setCanceledOnTouchOutside(false);
            } else if(!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
        } else {
            if(mWaitDialog != null && mWaitDialog.isShowing()) {
                mWaitDialog.cancel();
            }
        }
    }


    /**
     * 设置appbar通用布局的layout
     * @param layoutRes
     */
    public void setNavCustomLayout(@LayoutRes int layoutRes) {
        this.mNavCustomLayoutRes = layoutRes;
    }


    /**
     * 添加navbar的tab item
     * @param txtRes
     * @param imgRes
     * @param cls
     */
    public void addNavTab(@StringRes int txtRes, @DrawableRes int imgRes, Class<? extends BaseUIFragment> cls) {
        addNavTab(getString(txtRes), imgRes, cls);
    }

    /**
     * 添加navbar的tab item
     * @param title
     * @param imgRes
     * @param cls
     */
    public void addNavTab(String title, @DrawableRes int imgRes, Class<? extends BaseUIFragment> cls) {
        if(!withOption(UIOptions.UI_OPTIONS_NAVBAR_TABS)
                || cls == null) {
            return;
        }

        if( UtilString.isNotBlank(title)) {
            if (mNavTabs == null) {
                mNavTabs = new ArrayList<>(4);
            }

            FragmentTab tab = new FragmentTab();
            tab.setTitle(title);
            tab.setIcon(imgRes);
            tab.setFragmentClazz(cls);
            mNavTabs.add(tab);
        }
    }


    /**
     * 设置navbar tab的红点是否显示
     * @param index
     * @param visibility
     */
    public void setNavTabDotVisibility(int index, int visibility) {
        if(!withOption(UIOptions.UI_OPTIONS_NAVBAR_TABS)) {
            return;
        }

        if(mTabHost != null) {
            View viewTab = mTabHost.getTabWidget().getChildTabViewAt(index);
            View viewDot = viewTab.findViewById(R.id.base_id_tab_dot);
            viewDot.setVisibility(visibility);
        }
    }

    /**
     * 设置侧滑头部布局
     * @param layoutRes
     */
    public View setDrawerHeaderView(@LayoutRes int layoutRes) {
        if(mNvDrawer != null) {
            return mNvDrawer.inflateHeaderView(layoutRes);
        }

        return null;
    }

    /**
     * 设置侧滑菜单布局
     * @param menuRes
     */
    public void setDrawerMenu(@MenuRes int menuRes) {
        if(mNvDrawer != null) {
            mNvDrawer.inflateMenu(menuRes);
        }
    }

    /**
     * 设置侧滑menu点击事件
     * @param listener
     */
    public void setDrawerMenuItemSelectedListener(
            NavigationView.OnNavigationItemSelectedListener listener){
        if(mNvDrawer != null) {
            mNvDrawer.setNavigationItemSelectedListener(listener);
        }
    }

    /**
     *
     * @param gravity
     */
    public void openDrawer(int gravity) {
        if(mDlLayout != null) {
            mDlLayout.openDrawer(gravity);
        }
    }

    /**
     *
     * @param gravity
     */
    public void closeDrawer(int gravity) {
        if(mDlLayout != null) {
            mDlLayout.closeDrawer(gravity);
        }
    }

    /**
     *
     * @param gravity
     * @return
     */
    public boolean getDrawerState(int gravity) {
        return mDlLayout == null
                ? false : mDlLayout.isDrawerOpen(gravity);
    }


    /**
     * 是否有当前界面构造选项
     * @param option
     * @return
     */
    private boolean withOption(long option) {
        return (mOptions & option) != 0;
    }

    /**
     * 重试加载
     */
    private void retry() {
        if (mRetryListener != null) {
            mRetryListener.onRetry();
        }
    }

    /**
     * 创建tab item
     * @param txtRes
     * @param imgRes
     * @return
     */
    private View newTabIndicator(@StringRes int txtRes, @DrawableRes int imgRes) {
        return newTabIndicator(getString(txtRes), imgRes);
    }

    /**
     * 创建tab item
     * @param title
     * @param imgRes
     * @return
     */
    private View newTabIndicator(String title, @DrawableRes int imgRes) {
        View indicator = LayoutInflater.from(this)
                .inflate(R.layout.res_layout_base_navbar_tab_indicator, null);
        ImageView ivIcon = (ImageView) indicator.findViewById(R.id.base_id_tab_img);
        ivIcon.setBackgroundResource(imgRes);
        TextView tvName = (TextView)indicator.findViewById(R.id.base_id_tab_text);
        tvName.setText(title);
        return indicator;
    }

}
